package com.tanhua.interceptor;

import com.tanhua.domain.User;
import com.tanhua.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器，用于拦截token，解析token，并将信息放入threadLocal中
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    /**
     * 前置拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("前置拦截器");
        //1 获取token，解析token
        String token = request.getHeader("authorization");
        if (StringUtils.isBlank(token)){
           return false;
        }
        //解析token
        Claims claims = JWTUtil.parseToken(token, "tanhua");
        if (claims==null){
            return false;
        }
        Long userId = Long.valueOf(claims.get("userId").toString());
        String mobile = claims.get("mobile").toString();
        //构造user
        //2 将用户信息存入ThreadLocal
        User user = new User();
        user.setId(userId);
        user.setMobile(mobile);

        UserHolder.set(user);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("后置拦截器");
        UserHolder.remove();
    }
}
